package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

/**
 * ClassName: CacheClient
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.09.25 19:29
 */

@Component
@Slf4j
public class CacheClient {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //建立线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    public void set(String key, Object value, Long time, TimeUnit unit){
        String jsonStr = JSONUtil.toJsonStr(value);
        stringRedisTemplate.opsForValue().set(key, jsonStr, time, unit);
    }

    public void setWithLogicalTime(String key, Object value, Long time, TimeUnit unit){

        //设置逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        String jsonStr = JSONUtil.toJsonStr(redisData);
        stringRedisTemplate.opsForValue().set(key, jsonStr);
    }


    //解决缓存穿透的方案
    public <R, ID> R getPassThrough(String keyPre , ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){
        //1 从redis查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(keyPre + id);

        //2 判断是否存在
        if(StrUtil.isNotBlank(json)){
            //2.1 存在, 且不为空串
            return JSONUtil.toBean(json, type);
        }

        //2.1.1 不为null, 但为空字符串，防止缓存击穿
        if("".equals(json)){
            //return Result.fail("商户不存在");
            return null;
        }

        //2.2 不存在，调用者传入参数
        R object = dbFallback.apply(id);

        if(object == null){
            //3 数据库不存在，在redis存储空值，防止缓存穿透
            stringRedisTemplate.opsForValue().set(keyPre + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //return Result.fail("商户不存在");
            return null;
        }

        //4 数据库存在
        //4.1 数据同步缓存到redis
        //缓存有效期
        stringRedisTemplate.opsForValue().set(keyPre + id , JSONUtil.toJsonStr(object), time, unit);
        //也可set(keyPre + id, object, time, unit);

        //4.2 数据库返回数据给前端
        //return Result.ok(shop);
        return object;

    }



    //解决缓存击穿: 逻辑过期方案
    public <R, ID> R getLogicalTime(String keyPer, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){
        //1 从redis查询商铺缓存
        String ObjectJson = stringRedisTemplate.opsForValue().get(keyPer + id);

        //2 判断是否存在
        if(StrUtil.isBlank(ObjectJson)){
            //2.1 不存在, 返回null
            return null;
        }

        //2.2 存在，判断缓存逻辑时间是否过期
        //shopJson反序列化为Shop对象
        RedisData data = JSONUtil.toBean(ObjectJson, RedisData.class);
        LocalDateTime expireTime = data.getExpireTime();

        JSONObject json = (JSONObject) data.getData();
        R r = JSONUtil.toBean(json, type);

        if(expireTime.isAfter(LocalDateTime.now())){
            //2.2.1 未过期，直接返回店铺信息
            return r;
        }

        //2.2.2 过期，重建缓存信息
        //3 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);

        if(isLock){
            //开启独立线程
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查数据库
                    R r1 = dbFallback.apply(id);
                    //重新设置逻辑过期时间，并更新redis中数据
                    setWithLogicalTime(keyPer + id, r1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }
            });

        }
        return r;
    }


    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }


    private boolean unlock(String key){
        Boolean ifDelete = stringRedisTemplate.delete(key);
        return BooleanUtil.isTrue(ifDelete);
    }
}
